<template>
  <view class="edit-container">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">编辑展览</text>
      <button class="save-btn" @click="updateExhibition">更新</button>
    </view>

    <!-- 展览表单组件 -->
    <ExhibitionForm 
      ref="exhibitionFormRef"
      :initial-data="initialFormData"
      :hide-media="true"
    />
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { updateRecord } from '@/services/api/backendApi'
import ExhibitionForm from '@/components/ExhibitionForm.vue'

// 表单组件引用
const exhibitionFormRef = ref(null)

// 初始表单数据
const initialFormData = ref({})
const originalId = ref(null)

// 页面加载时初始化数据
onLoad((query) => {
  if (query && query.data) {
    try {
      const exhibitionData = JSON.parse(decodeURIComponent(query.data))
      initialFormData.value = exhibitionData
      originalId.value = exhibitionData.id || exhibitionData.recordId
      console.log('进入编辑模式，展览ID:', originalId.value)
    } catch (e) {
      console.error('解析展览数据失败', e)
    }
  }
})

// 更新展览
async function updateExhibition() {
  // 获取表单组件的数据和验证结果
  const formData = exhibitionFormRef.value?.getFormData()
  const isValid = exhibitionFormRef.value?.validateForm()
  
  if (!isValid || !formData) {
    return
  }
  
  // 准备更新的数据
  const exhibitionData = {
    ...formData,
    id: originalId.value,
    recordId: originalId.value,
    updatedAt: new Date().toISOString(),
    // 为了兼容艺术足迹页面的显示，添加location字段
    location: formData.museum
  }
  
  // 更新到后端数据库
  console.log('=== 开始更新展览 ===');
  console.log('展览数据:', exhibitionData);
  
  try {
    // 调用API更新展览记录
    const recordData = {
      recordId: originalId.value,
      title: exhibitionData.title,
      galleryName: exhibitionData.museum,
      exhibitionDate: exhibitionData.date,
      country: exhibitionData.country || '',
      city: exhibitionData.city || '',
      artist: exhibitionData.artist || '',
      styleTags: exhibitionData.styleTags || '',
      notes: exhibitionData.notes || '',
      aiSummary: exhibitionData.aiSummary || ''
    };
    
    console.log('📤 调用更新展览记录API:', recordData);
    const updateResult = await updateRecord(recordData);
    console.log('✅ 展览记录更新成功:', updateResult);
    
    // 通过事件总线通知艺术足迹页面更新数据
    uni.$emit('exhibitionSaved', exhibitionData);
    
    uni.showToast({ title: '更新成功', icon: 'success' });
    
  } catch (error) {
    console.error('❌ 更新展览失败:', error);
    
    // 如果API未实现，使用模拟数据
    if (error.message && error.message.includes('404')) {
      console.log('🔄 API未实现，使用模拟数据');
      // 编辑模式：保持原有ID
      exhibitionData.id = originalId.value;
      exhibitionData.recordId = originalId.value.toString();
      
      // 通过事件总线通知艺术足迹页面更新数据
      uni.$emit('exhibitionSaved', exhibitionData);
      
      uni.showToast({ title: '更新成功（模拟）', icon: 'success' });
    } else {
      uni.showToast({ title: '更新失败，请重试', icon: 'error' });
      return
    }
  }
  
  // 返回上一页
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}
</script>

<style lang="scss" scoped>
.edit-container {
  min-height: 100vh;
  background: #1a1a1a;
  padding: 40rpx;
  padding-bottom: 240rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 48rpx;
  
  .title {
    font-size: 26px;
    font-weight: 700;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
  
  .save-btn {
    background: linear-gradient(135deg, #ff0050, #ff4081);
    color: #ffffff;
    border: none;
    border-radius: 40rpx;
    padding: 16rpx 40rpx;
    font-size: 14px;
    font-weight: 600;
    left: 100px;
  }
}
</style>